package topic;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

/**
 * TODO
 *
 * @author gaoxiang
 * @date 2021/7/2723:59
 */
public class TopicSend {
    public static void main(String[] args) throws Exception{
        ConnectionFactory factory=new ConnectionFactory();
        factory.setHost("121.41.192.69");//设置RabbitMQ的主机IP
        factory.setPort(5672);//设置RabbitMQ的端口号
        factory.setUsername("guest");//设置访问用户名
        factory.setPassword("guest");//设置访问密码
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        //声明交换机- channel.exchangeDeclare(交换机名字,交换机类型,持久化)
        channel.exchangeDeclare("exchange_top", BuiltinExchangeType.TOPIC,true);
        //连续发5条消息
        for (int i = 0; i < 5; i++) {
            String routingKey = "";
            //发送消息的时候根据相关逻辑指定相应的routing key。
            switch (i){
                case 0:  //假设i=0，为error消息
                    routingKey = "log.error";
                    break;
                case 1: //假设i=1，为info消息
                    routingKey = "log.info";
                    break;
                case 2: //假设i=2，为warning消息
                    routingKey = "log.warning";
                    break;
                case 3: //假设i=3，为log.info.add消息
                    routingKey = "log.info.add";
                    break;
                case 4: //假设i=4，为log.info.update消息
                    routingKey = "log.info.update";
                    break;
            }
            //10、创建消息-String m = xxx
            String message = "hello,message！" + i;
            //11、消息发送-channel.basicPublish(交换机[默认Default Exchage],路由key[简单模式可以传递队列名称],消息其它属性,消息内容)
            channel.basicPublish("exchange_top",routingKey,null,message.getBytes("utf-8"));
            System.out.println("消息发送成功"+i);
        }
        //12、关闭资源-channel.close();connection.close()
        channel.close();
        connection.close();
    }
}
